package com.yuezhi.acl.security.handler;

import com.yuezhi.utils.R;
import com.yuezhi.utils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  退出处理类
 **/
public class MyLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public MyLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate){
        this.tokenManager=tokenManager;
        this.redisTemplate=redisTemplate;
    }
    public MyLogoutHandler(){}
    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        String token = httpServletRequest.getHeader("token");
        if(token != null){
            //移除
            tokenManager.removeToken(token);
            //从token获取用户名
            String username = tokenManager.getUserInfoFromToken(token);
            redisTemplate.delete(username);
        }
        ResponseUtil.out(httpServletResponse, R.success());
    }
}
